//
// Created by v on 19-6-27.
//

#ifndef JKLIBS_CMMQTTBASE_H
#define JKLIBS_CMMQTTBASE_H

#include <iostream>

class CMMqttFunction
{
  public:
    virtual void onLog(int level, const char *str){};

    virtual void onPublish(int id, int resultCode){};

    virtual void onMessage(int id, const char *topic, const char *data,
                           size_t datalen){};

    virtual void onConnect(int result){};

    virtual void onDisconnect(int result){};

    virtual void onSubscribe(int id){};

    void *getHandler() { return m_handler; }

    void setHandler(void *h) { m_handler = h; }

  private:
    void *m_handler;
};

class CMMqttBase
{
  public:
    CMMqttBase(const char *host, int port);
    virtual ~CMMqttBase();

    void setFunction(CMMqttFunction *f) { m_function = f; }

    void setDebug(bool d) { m_debug = d; }
    void setId(const char *id) { m_id = id; }

    void setKeepAlive(int interval) { m_keepAlive = interval; }

    void setTls(const char *cafile, const char *capath, const char *certfile,
                const char *keyfile)
    {
        if (!cafile && !capath)
            return;
        m_withTls = true;
        if (cafile)
            m_cafile = cafile;
        if (capath)
            m_capath = capath;
        if (certfile)
            m_certfile = certfile;
        if (keyfile)
            m_keyfile = keyfile;
    }
    void setTlsInsecure() { m_insecureTls = true; }

    virtual int setUsername(const char *user, const char *pass) { return -1; }

    virtual int init() { return 0; }
    virtual int deinit() { return 0; }

    virtual int connect()    = 0;
    virtual int disconnect() = 0;
    virtual int reconnect()  = 0;

    virtual int loop()       = 0;
    virtual int loop_block() = 0;

    virtual int setWill(const char *topic, const char *data) = 0;
    virtual int sub(const char *topic, int qos)              = 0;
    virtual int pub(const char *topic, const char *data)     = 0;

  protected:
    std::string m_host;
    int         m_port;
    std::string m_id;

    bool        m_withTls;
    std::string m_cafile;
    std::string m_capath;
    std::string m_certfile;
    std::string m_keyfile;

    std::string m_username;
    std::string m_password;

    bool m_insecureTls;

    int m_keepAlive;

    bool            m_sessionClean;
    CMMqttFunction *m_function;
    bool            m_debug;
    bool            m_connected;

    std::string m_willTopic;
    std::string m_willData;
    int         m_willQoS;
    int         m_willRetain;
};

#endif // JKLIBS_CMMQTTBASE_H
